<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Str;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $e)
    {
        // TODO 后台接口错误统一返回错误信息
        // $code = $e->getCode();
        // if ($code && $request->is('api/admin/*')) {
        //     $message = $e->getMessage();
        //     if ($code == 401) $message =  'Unauthorized';
        //     return response($message, $code);
        // }

        // // TODO 小程序接口错误统一返回错误信息
        // if ($request->is('api/miniapp/*')) {
        //     logs()->info('api/miniapp error', ['exception' => $e]);
        //     if ($code == 401) {
        //         return response('Unauthorized', 401);
        //     }
        // }

        if ($request->is("api/admin/*") || $request->is("api/miniapp/*")) {
            if ($e instanceof ValidationException) {
                return response($e->errors());
            }
            if (Str::contains($e->getMessage(), "No query results for model")) {
                return response("数据不存在或已被删除", 500);
            }
        }

        if (401 === $e->getCode()) {
            return response('Unauthorized', 401);
        }

        return parent::render($request, $e);
    }
}
